package com.vitogiovanni.tobook;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import android.app.ListFragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.vitogiovanni.tobook.entity.localeendpoint.model.Locale;
import com.vitogiovanni.tobook.utilities.LocaleItem;
import com.vitogiovanni.tobook.utilities.LocaliListViewAdapter;
import com.vitogiovanni.tobook.utilities.NetworkChecker;


/**
 * A placeholder fragment containing a simple view.
 */
public class ListaLocaliFragment extends ListFragment{
	
	private LocaliListViewAdapter adapter;
	/**
	 * The fragment argument representing the section number for this
	 * fragment.
	 */
	private static final String ARG_SECTION_NUMBER = "section_number";
	private ListView listView;
	private List<LocaleItem> locali = new ArrayList<LocaleItem>();
	private View rootView;
	/**
	 * Returns a new instance of this fragment for the given section number.
	 */
	public static ListaLocaliFragment newInstance(int sectionNumber) {
		ListaLocaliFragment fragment = new ListaLocaliFragment();
		Bundle args = new Bundle();
		args.putInt(ARG_SECTION_NUMBER, sectionNumber);
		fragment.setArguments(args);
		return fragment;
	}

	public ListaLocaliFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_lista_locali,
				container, false);
		
		
		listView = (ListView) rootView.findViewById(android.R.id.list);
        adapter = new LocaliListViewAdapter(getActivity().getApplicationContext(),R.layout.list_items_locali, locali);
        listView.setAdapter(adapter);
		
		return rootView;
	}

	public void updateListaLocali(List<Locale> listLocali, String[] distanzaLocale){
		
		int i=0;
		for(Locale loc: listLocali){
			
			Bitmap bitmap;
			
			if(loc.getAvatar()!=null){
				byte[] img = loc.getAvatar().decodeFoto();
				if (img == null) {
					bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.default_icon_locale);
				} else {
					ByteArrayInputStream inputStream = new ByteArrayInputStream(img);
					final BitmapFactory.Options options = new BitmapFactory.Options();
					options.inSampleSize = 2;
					bitmap = BitmapFactory.decodeStream(inputStream, null, options);
					try {
						inputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}else{
				bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.default_icon_locale);
			}
			
			List<String> tipologieLocaleTemp = new ArrayList<String>();
			for(int j=0; j<loc.getTipologia().size(); j++){
				tipologieLocaleTemp.add(loc.getTipologia().get(j).getName());
			}

			String tipiLocale = TextUtils.join(", ", tipologieLocaleTemp);
			
			LocaleItem item = new LocaleItem(loc.getId().toString(), loc.getNome(), loc.getVia(), loc.getCitta(), tipiLocale, bitmap, distanzaLocale[i]);
			locali.add(item);
			adapter.sort(new Comparator<LocaleItem>(){
	        	public int compare(LocaleItem arg0, LocaleItem arg1) {
	        		Float dist0, dist1;
	        		if(arg0.getDistanza().equals("--") || arg1.getDistanza().equals("--"))
	        		{
	        			return 0;
	        		}
	        		dist0 = Float.valueOf(arg0.getDistanza());
	        		dist1 = Float.valueOf(arg1.getDistanza());
	                return dist0.compareTo(dist1);
	            }
	        });
			((BaseAdapter) listView.getAdapter()).notifyDataSetChanged();
			i++;
		}
	}
	
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
	
		Intent intentLocale = new Intent(getActivity(), LocaleActivity.class);
		
		String idLocale = adapter.getItem(position).getId();
		String nomeLocale = adapter.getItem(position).getNome();
		intentLocale.putExtra("idLocale", idLocale);
		intentLocale.putExtra("nomeLocale", nomeLocale);
		if (!NetworkChecker.isInternetAvailable(getActivity().getApplicationContext())) {
			NetworkChecker.noConnectionToast(getActivity().getApplicationContext());
			return;
		}
		startActivity(intentLocale);
	}

}
